<template>
  <el-container class="GoodSkuData">
    <el-header class="mt20 flex">
      <span class="title fs18 mr10">Sku列表</span>
      <el-divider />
    </el-header>
    <el-main v-loading="loading">
      <el-row class="GoodSkuData-title" style="padding: 15px 0px 15px 30px;text-align: center;font-size: 16px;">
        <el-col :span="3">上架时间</el-col>
        <el-col :span="3">商品封面</el-col>
        <el-col :span="3">商品名称</el-col>
        <el-col :span="3">商品标签</el-col>
        <el-col :span="2">商品类别</el-col>
        <el-col :span="2">商品库存</el-col>
        <el-col :span="2">是否无规格商品</el-col>
        <el-col :span="6">操作</el-col>
      </el-row>
      <el-collapse v-model="activeNames" class="GoodSkuData-collapse">
        <el-collapse-item v-for="(item, index) in tableData" :key="index" :name="item.id">
          <!-- 商品信息 -->
          <el-row slot="title" :gutter="20" class="flex fs15" style="width: 100%;height: 100%;text-align: center;margin: 0;">
            <el-col :span="3">{{ item.createTime | setTime }}</el-col>
            <el-col :span="3"><Cimage :src="item.iconId[0].url" fit="cover" style="cursor: pointer;border-radius: 5px;" width="50px" height="50px" @click.stop.native="openViewr(item.iconId[0].url)" /></el-col>
            <el-col :span="3" class="twoLineEllipsis">{{ item.name | isNullData }}</el-col>
            <el-col :span="3">{{ item.hot | isNullData }}</el-col>
            <el-col :span="2">{{ item.typeName | isNullData }}</el-col>
            <el-col :span="2">{{ item.stock_num | isNullData }}</el-col>
            <el-col :span="2">{{ item.none_sku ? '是' : '否' }}</el-col>
            <el-col :span="6">
              <Cbutton icon="el-icon-search" size="small" @click.native.stop="toDetailsGoods(item.id)">查看</Cbutton>
              <Cbutton type="pink" icon="el-icon-plus" size="small" class="ml10" @click.native.stop="openDialog(item, 'select')">编辑类目</Cbutton>
              <!-- <el-button type="info" icon="el-icon-search" size="small" @click="toDetailsGoods(item.id)">查看</el-button> -->
              <!-- <el-button size="small" icon="el-icon-plus" type="primary" @click.stop="openDialog(item, 'add')">添加列表</el-button> -->
            </el-col>
          </el-row>
          <!-- 该商品下的sku列表 -->
          <el-row v-for="(it, idx) in item.skuList" :key="idx" :gutter="20" class="flex fs15 mb15" style="align-items: center;width: 100%;height: 100%;">
            <el-col :span="3"><span>{{ idx + 1 }}、 </span> {{ it.createTime | setTimeMini }}</el-col>
            <el-col :span="3">{{ it.k | isNullData }}</el-col>
            <el-col :span="18" class="flex" style="align-items: center;">
              <div v-for="val in it.v" :key="val.id" class="flex">
                <Cimage v-if="val.previewImgUrl" :preview-src-list="[val.previewImgUrl[0].url]" :src="val.previewImgUrl[0].url" width="30px" height="30px" fit="cover" style="border: 1px solid #f7c1da;border-radius: 4px;" />
                <el-tag class="tagSku mr20" size="medium" effect="plain">
                  <span class="ml5 mr5 fs15">{{ val.name }}</span>
                  <i class="el-icon-edit-outline fs18" @click="openDialog(val, 'modify', it.id, item.id)" />
                  <el-popconfirm
                    title="确定要执行该操作吗？"
                    @confirm="hanbleGoodsSku(val, it.k_s)"
                  >
                    <i slot="reference" class="el-icon-close" />
                  </el-popconfirm>
                </el-tag>
              </div>
              <Cbutton size="small" type="pink" style="height: 30px;" icon="el-icon-plus" @click.native="openDialog({}, 'add', it.id, item.id)">添加</Cbutton>
              <!-- <el-button size="medium" icon="el-icon-plus" type="primary" plain style="height: 40px;" @click="openDialog({}, 'add', item.id)">添 加</el-button> -->
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-main>
    <Cdialog
      :visible="dialog.visible"
      :title="dialog.title"
      width="350px"
      class="GoodSkuData-dialog"
      @handleClose="handleClose"
    >
      <div v-if="dialog.type === 'add' || dialog.type === 'modify'" class="GoodSkuData-dialog-content flexColCenter pt5 pb5 pl10 pr10">
        <CuploadImageOnce :external-image-url.sync="dialog.item.previewImgId" />
        <Cinput v-model="dialog.item.name" placeholder="请输入类目名称" style="width: 100%;" class="mt30">输入类目名称</Cinput>
      </div>
      <div v-else class="pt5 pb5 pl10 pr10">
        <p style="margin: 10px 0;">请选择Sku类目：</p>
        <el-drag-select v-model="dialog.selectSku" multiple placeholder="请选择要添加的商品规格类目" style="width: 100%;" @change="selectSkuChange" @dragChange="selectSkuChange">
          <el-option
            v-for="item in dialog.skuList"
            :key="item.k_s"
            :label="item.k"
            :value="item.k_s"
          />
        </el-drag-select>
      </div>
      <div slot="footer" class="flexCenter">
        <Cbutton v-if="dialog.type === 'add' || dialog.type === 'modify'" size="small" @click.native="handleClose">取 消</Cbutton>
        <Cbutton v-if="dialog.type === 'add' || dialog.type === 'modify'" type="pink" size="small" class="ml10" @click.native="saveSku">保 存</Cbutton>
        <Cbutton v-if="dialog.type ==='select'" type="pink" size="small" @click.native="handleClose">关 闭</Cbutton>
      </div>
    </Cdialog>
  </el-container>
</template>
<script>
import {
  categoryGetTwo
} from '@/api/category'
import {
  myGoodsDetail,
  myGoodsList,
  myGoodsModify
} from '@/api/myGoods'
import {
  goodsSkuTypeModifySkuType,
  goodsSkuTypeDeleteSku,
  goodsSkuGetSkuList
} from '@/api/goodsSku'
import CuploadImageOnce from '@/components/CuploadImageOnce'
export default {
  components: { CuploadImageOnce },
  data() {
    return {
      loading: true,
      activeNames: [],
      tableData: [], // 主数据

      listQuery: {
        total: 0,
        page: 1,
        size: 10,
        value: '' // 模糊搜索字段
      },
      dialog: {
        visible: false,
        title: '',
        type: '',
        item: '', // 修改类目的item数据（用于sku规格类目）
        skuId: '', // sku大类id
        goodsId: '', // 当前的商品id

        skuList: [], // sku大类数据
        selectSku: [] // 已选择的sku大类列表
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 级联选择器商品规格类目的修改删除 回调
    async selectSkuChange() {
      const res = await myGoodsModify({
        id: this.dialog.item.id,
        sku: this.dialog.selectSku.toString()
      })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getList()
      }
    },
    // 删除商品的类目Sku值
    async hanbleGoodsSku(item, key) {
      const res = await goodsSkuTypeDeleteSku({ id: item.id, key: key })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getList()
      }
    },
    // 对话框点击保存（商品规格）修改或增加sku小类规格id
    async saveSku() {
      if (!this.dialog.item.name) {
        this.$message.error('请输入类目名称')
        return
      }
      const res = await goodsSkuTypeModifySkuType({
        id: this.dialog.item.id ? this.dialog.item.id : undefined,
        skuId: this.dialog.skuId,
        goodsId: this.dialog.goodsId,
        name: this.dialog.item.name,
        imgId: this.dialog.item.previewImgId
      })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getList()
        this.handleClose()
      }
    },
    // 关闭弹窗
    handleClose() {
      this.dialog = {
        visible: false,
        title: '',
        type: '',
        item: '', // 修改类目的item数据（用于sku规格类目）
        skuId: '', // sku大类id
        goodsId: '', // 当前的商品id

        skuList: [], // sku大类数据
        selectSku: [] // 已选择的sku大类列表
      }
    },
    // 打开弹窗
    openDialog(item, type, skuId, goodsId) {
      switch (type) {
        case 'modify':
          item['previewImgId'] = ''
          this.dialog.title = '修改类目'
          this.dialog.skuId = skuId
          this.dialog.goodsId = goodsId
          if (item.previewImgUrl) item['previewImgId'] = item.previewImgUrl[0].url
          break
        case 'add':
          item['previewImgId'] = ''
          this.dialog.skuId = skuId
          this.dialog.goodsId = goodsId
          this.dialog.title = '新增类目'
          break
        case 'select':
          this.getgoodsSkuGetSkuList() // 打开对话框时再获取数据
          this.dialog.title = '修改Sku'
          this.dialog.selectSku = item.sku.split(',')
          break
      }
      this.dialog.type = type
      this.dialog.visible = true
      this.dialog.item = item
      console.log(this.dialog, '对话框')
    },
    // 跳转商品详情
    toDetailsGoods(id) {
      this.$router.push({
        name: 'GoodsDetails',
        path: '/goods/details',
        query: { id: id }
      })
    },
    // 获取sku大类数据
    async getgoodsSkuGetSkuList() {
      const res = await goodsSkuGetSkuList({
        page: 1,
        size: 9999
      })
      if (res.code === 0) {
        const { data } = res
        this.dialog.skuList = data.list
      }
    },
    // 初始化数据
    async getList() {
      const good_res = await myGoodsList(this.listQuery) // 查询商品
      if (good_res.code === 0) {
        const { data: goodData } = good_res
        const value = await this.filterCategory(goodData.list)
        let flag = 0
        for (let i = 0; i < value.length; i++) {
          myGoodsDetail({ goodsId: value[i].id }).then(goodsDetail_res => {
            if (goodsDetail_res.code === 0) {
              const { data: goodsDetail_data } = goodsDetail_res
              value[i] = { typeName: value[i].typeName, ...goodsDetail_data }
              flag++
              if (flag === value.length) {
                this.tableData = value
                this.loading = false
                this.listQuery.total = goodData.total
                this.activeNames = this.tableData[0].id // 手风琴默认显示第一行
                console.log(this.tableData, '商品规格列表数据')
              }
            }
          })
        }
      }
    },
    // 商品分类匹配
    filterCategory(list) {
      return new Promise(resolve => {
        if (list.length === 0) {
          resolve(list)
          return
        }
        categoryGetTwo().then(res => { // 直接获取全部二级分类
          if (res.code === 0) {
            const { data } = res
            list.forEach(item => {
              const index = data.findIndex(v => item.parentId === v.id)
              item['typeName'] = data[index].name || '未命名分类'
            })
            resolve(list)
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/element-variables.scss";
.GoodSkuData{
  &-title{
    background-color: rgba($color: $--color-primary, $alpha: .09);
  }
  &-collapse{
    border-top: 0;
    border-bottom: 0;
    ::v-deep .el-collapse-item{
      margin: 20px 0;
      &__header{
        flex-direction: row-reverse;
        height: inherit;
        line-height: inherit;
        padding: 10px 0;
        border-bottom: 0;
        // background-color: #e9f2ff;
        background-color: rgba($color: $--color-primary, $alpha: .09);
      }
      &__arrow{
        font-size: 16px;
        font-weight: bold;
        margin: 0;
        margin-left: 15px;
      }
      &__wrap{
        border-bottom: 0;
      }
      &__content{
        background-color: rgba($color: $--color-primary, $alpha: .05);
        padding: 10px 0 10px 40px;
      }
    }
  }
}
.tagSku{
  display: inline-flex;
  align-items: center;
  margin-right: 15px;
  letter-spacing: 2px;
  height: 30px;
  line-height: initial;
  ::v-deep .el-icon-close{
    font-size: 22px;
    height: 22px;
    width: 22px;
    line-height: 25px;
  }
  ::v-deep .el-icon-close:hover{
    color: #FFFFFF;
    background-color: $--color-primary;
  }
  ::v-deep .el-icon-edit-outline{
    cursor: pointer;
  }
  ::v-deep .el-icon-edit-outline:hover{
    color: #FFFFFF;
    background-color: $--color-primary;
  }
}
</style>
